package org.dxy.domain.handler.route;

import com.google.common.eventbus.EventBus;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dxy.domain.port.CommandHandler;
import org.dxy.domain.port.repository.IRouteRepository;
import org.dxy.domain.command.route.RouteEnableCommand;
import org.dxy.domain.model.aggregate.Route;
import org.dxy.types.common.CommandResult;
import org.springframework.stereotype.Component;

/**
 * @description: 启用工艺路线命令处理器
 * @author: dxy
 * @createTime: 2025/6/26 10:30
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class RouteEnableCommandHandler implements CommandHandler<RouteEnableCommand, Void> {

    private final IRouteRepository routeRepository;
    private final EventBus eventBus;

    @Override
    public CommandResult<Void> handle(RouteEnableCommand command) {
        Route route = routeRepository.findById(command.routeId());
        if (route == null) {
            log.error("未找到工艺路线，command={}", command);
            return CommandResult.fail("工艺路线不存在");
        }

        route.enable(command);
        routeRepository.save(route);
        route.getDomainEvents().forEach(eventBus::post);
        route.clearDomainEvents();
        
        log.info("启用工艺路线成功, command={}", command);
        return CommandResult.success("启用工艺路线成功");
    }
} 